/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import Database.Database;
import Database.Table;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

/**
 *
 * @author PHAMDANH
 */
public final class ModifyPanel extends JScrollPane{
    //private JTabbedPane tabbedPane;    
    private Database database;
    private JTable jtable;
    private JPopupMenu popup;          
    private int rowSelected = -1;
    private int colSelected = -1;
    private Table table;
    private String[] columnNames = new String[]{"PK","Column name","Data type","Allow nulls"};
    private Object[][] data = null;
    public ModifyPanel(Database db, Table table)
    {
        this.database = db;  
        this.table = table;        
        jtable = new JTable();                
        jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        InitTableModel();              
        popup = new JPopupMenu();        
        popup.add(act_setPrimaryKey);        
        jtable.add(popup);
        jtable.addMouseListener(new PopupTrigger());                
        this.setViewportView(jtable);
        
    }
    public Database getDatabase()
    {
        return database;
    }
    public Table getTable()
    {
        return table;
    }
    public void InitTableModel()
    {        
        int size = table.getColumns().size();
        data = new Object[size+1][4];  
        for(int i=0; i<size; i++)
        {
            data[i][0] =  table.isPrimaryKeyColumn(table.getColumns().get(i).getName());
            data[i][1]= table.getColumns().get(i).getName();
            Class type = table.getColumns().get(i).getType();            
            if(type==String.class)
                data[i][2]= "String";
            else
                data[i][2]= "Integer";
            data[i][3]= table.getColumns().get(i).getAllowNull();            
        }        
        data[size][0] = null;
        data[size][1] = null;
        data[size][2] = null;
        data[size][3] = null;
        MyTableModel model = new MyTableModel(data, columnNames);
        jtable.setModel(model);
        
        TableColumn colPK = jtable.getColumnModel().getColumn(0);
        colPK.setCellRenderer(new IconCellRenderer());
        colPK.setPreferredWidth(30);
        
        TableColumn colName = jtable.getColumnModel().getColumn(1);
        colName.setPreferredWidth(200);
        colName.setCellRenderer(new ColumnNameCellRenderer(this));
        
        String[] items = new String[]{"String","Integer"};
        TableColumn colType = jtable.getColumnModel().getColumn(2);
        colType.setCellEditor(new DefaultCellEditor(new JComboBox(items)));
        colType.setCellRenderer(new ComboBoxCellRenderer(items,table));
        colType.setPreferredWidth(100);
        
        TableColumn colAllowNull = jtable.getColumnModel().getColumn(3);
        colAllowNull.setCellEditor(new DefaultCellEditor(new JCheckBox()));
        colAllowNull.setCellRenderer(new CheckboxCellRenderer(items,table));
        colAllowNull.setPreferredWidth(70);  
    }
    
    private AbstractAction act_deleteColumn = new AbstractAction("Delete Column") 
    { 
        @Override
        public void actionPerformed(ActionEvent e)
        {             
            if(!table.RemoveColumn(rowSelected))
                JOptionPane.showMessageDialog(null, "Không thể delete column");
            else
                InitTableModel();  
        }
    };
    private AbstractAction act_setPrimaryKey = new AbstractAction("Add to primary key") 
    { 
        @Override
        public void actionPerformed(ActionEvent e)
        {            
            Object value = jtable.getModel().getValueAt(rowSelected, 0);
            if(!(Boolean)value)
            {                
                String key=jtable.getModel().getValueAt(rowSelected, 1).toString();
                if(!database.AddPrimaryKeyColumn(key,table.getName()))
                    JOptionPane.showMessageDialog(null, "Không thể thêm vào khóa chính");                    
                else
                {
                    jtable.getModel().setValueAt(true, rowSelected, 0);      
                    jtable.getModel().setValueAt(false, rowSelected, 3);
                }
            }
            
        }
    };
    private AbstractAction act_setRelationship = new AbstractAction("Set relationship") 
    { 
        @Override
        public void actionPerformed(ActionEvent e)
        {            
            String tableName = table.getName();
            RelationshipsForm relation = new RelationshipsForm(database,tableName);
            relation.pack();
            relation.setVisible(true);
        }
    };
    private AbstractAction act_removePrimaryKey = new AbstractAction("Remove primary key") 
    { 
        @Override
        public void actionPerformed(ActionEvent e)
        {            
            Object value = jtable.getModel().getValueAt(rowSelected, 0);
            if((Boolean)value)
            {                
                String key = jtable.getModel().getValueAt(rowSelected, 1).toString();
                if(!database.RemovePrimaryKeyColumn(key,table.getName()))
                {                        
                    JOptionPane.showMessageDialog(null, "Không thể xóa khỏi khóa chính");
                }
                else
                    jtable.getModel().setValueAt(false, rowSelected, 0);  
            }
        }
    };
    private class PopupTrigger extends MouseAdapter
    {
        @Override
        public void mouseReleased(MouseEvent e)
        {            
            if (e.isPopupTrigger())
            {
                int x = e.getX();
                int y = e.getY();         
                JTable source = (JTable)e.getSource();
                rowSelected = source.rowAtPoint( e.getPoint() );                
                colSelected = source.columnAtPoint(e.getPoint());                
                popup.removeAll();                
                if(rowSelected<table.getColumns().size())
                {
                    Object value = jtable.getModel().getValueAt(rowSelected, 0);
                    if(!(Boolean)value)
                    {                    
                        popup.add(act_setPrimaryKey);
                    }
                    else
                    {
                        popup.add(act_removePrimaryKey);
                    }
                    popup.add(act_deleteColumn);
                    popup.add(act_setRelationship);                                        
                }
                if(rowSelected!=-1)
                {
                    popup.show(jtable, x, y);
                }                
            }
        }
    }

}

